﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using BitPortal.Business;
using BitPortal.Models;
using BitPortal.Utils;

namespace BitPortal.Admin.Product.Category
{
    public partial class Default : Controls.BaseAdminPage
    {
        protected override void OnInit(EventArgs e)
        {
            PermissionBLL.CheckRoleThrowException(role: "ProductView", useExceptionHandler: true);
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindTreeNode();
            }
        }

        #region Bind TreeView Data
        protected void BindTreeNode()
        {
            Ext.Net.TreeNode node = CreateNode(null);
            TreePanel1.Root.Add(node);
            TreePanel1.RootVisible = true;
        }
        #endregion

        protected Ext.Net.TreeNode CreateNode(ProductCategory category)
        {
            //add curent category
            Ext.Net.TreeNode node = new Ext.Net.TreeNode("Nhóm gốc (không thể sửa/xóa)");
            node.NodeID = "0";
            if (category != null)
            {
                node.NodeID = category.CategoryID.ToString();
                node.Text = category.Name;
                node.Qtip = category.Description;
            }
            //add childs categories 
            foreach (ProductCategory ac in category.GetChilds())
            {
                node.Nodes.Add(CreateNode(ac));
            }
            //return node
            return node;
        }

        #region TreeView Event
        protected void TreePanel1_RemoteRename(object sender, RemoteRenameEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("ProductEdit");
                e.Accept = true;
                int Id = Convert.ToInt32(e.NodeID);
                ExtendedBitPortalEntities bitExt = new ExtendedBitPortalEntities();
                ProductCategory ac = bitExt.ProductCategories.SingleOrDefault(ent => ent.CategoryID == Id);
                if (ac != null)
                {
                    ac.Name = e.NewText;
                    bitExt.SaveChanges();
                }
                ShowNotification("Sửa đổi thành công nhóm sản phẩm mã : " + e.NodeID);
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }

        }

        protected void TreePanel1_RemoteRemove(object sender, RemoteActionEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("ProductDelete");
                ProductCategoryBLL.Delete(e.NodeID.ToInt32TryParse());
                e.Accept = true;
                ShowNotification("Xóa thành công nhóm sản phẩm mã : " + e.NodeID);
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        protected void TreePanel1_RemoteAppend(object sender, RemoteAppendEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("ProductInsert");
                e.Accept = true;
                ProductCategory category = new ProductCategory()
                {
                    Name = e.Text,
                    ParentID = (e.ParentNodeID.Equals("0")) ? null : (int?)Convert.ToInt32(e.ParentNodeID),
                    IsEnabled = true,
                    IsDeleted = false
                };
                category.Insert();
                ShowNotification("Thêm thành công nhóm sản phẩm : " + e.Text);
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        protected void BindFormData(int categoryID)
        {
            ProductCategory category = ProductCategoryBLL.GetByID(categoryID);
            if (category != null)
            {
                txtCategoryID.Text = category.CategoryID.ToString();
                txtName.Text = category.Name;
                txtDescription.Text = category.Description;
                txtSortOrder.Text = category.SortOrder.ToString();
                ckAllowUserPost.Checked = category.AllowUserPost;
                ckEnabled.Checked = category.IsEnabled;
                ckEnabledThumbnail.Checked = category.EnabledThumbnail;
                txtMetaDescription.Text = category.Meta.MetaDescription;
                txtMetaKeyword.Text = category.Meta.MetaKeyword;
                txtMetaTitle.Text = category.Meta.MetaTitle;
            }
        }

        protected void SubmitNode(object sender, DirectEventArgs e)
        {
            string nodeStr = e.ExtraParams["node"];
            Newtonsoft.Json.Linq.JObject node = JSON.Deserialize<Newtonsoft.Json.Linq.JObject>(nodeStr);
            string id = node.Property("nodeID").Value.ToString().Replace("\"", "");
            string path = node.Property("path").Value.ToString();
            //string task = node.SelectToken("attributes.task").ToString();
            BindFormData(Convert.ToInt32(id));
            Window1.Show();
        }

        protected void btnUpdate_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("ProductEdit");
                int Id = Convert.ToInt32(txtCategoryID.Text);
                ExtendedBitPortalEntities bitExt = new ExtendedBitPortalEntities();
                ProductCategory ac = bitExt.ProductCategories.SingleOrDefault(ent => ent.CategoryID == Id);
                if (ac != null)
                {
                    ac.Name = txtName.Text.Trim();
                    ac.Description = txtDescription.Text;
                    ac.SortOrder = Convert.ToInt32(txtSortOrder.Text);
                    ac.IsEnabled = ckEnabled.Checked;
                    ac.AllowUserPost = ckAllowUserPost.Checked;
                    ac.EnabledThumbnail = ckEnabledThumbnail.Checked;
                    ac.Meta.MetaTitle = txtMetaTitle.Text;
                    ac.Meta.MetaKeyword = txtMetaKeyword.Text;
                    ac.Meta.MetaDescription = txtMetaDescription.Text;
                    bitExt.SaveChanges();
                }
                ShowNotification("Sửa đổi thành công nhóm sản phẩm mã : " + txtCategoryID.Text);
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        protected void TreePanel1_RemoteMove(object sender, RemoteMoveEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("ProductEdit");
                int Id = Convert.ToInt32(e.NodeID);
                ExtendedBitPortalEntities bitExt = new ExtendedBitPortalEntities();
                ProductCategory ac = bitExt.ProductCategories.SingleOrDefault(ent => ent.CategoryID == Id);
                if (ac != null)
                {
                    ac.ParentID = (e.TargetNodeID.EndsWith("0")) ? null : (int?)Convert.ToInt32(e.TargetNodeID);
                    e.Accept = (bitExt.SaveChanges() > 0);
                }
                ShowNotification("Sửa đổi thành công nhóm sản phẩm mã : " + e.NodeID);
                e.Accept = true;
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }
        #endregion

        #region Trash menthods
        protected void BindTrash()
        {
            Store1.DataSource = (new ExtendedBitPortalEntities()).ProductCategories.Where(ent => ent.IsDeleted == true);
            Store1.DataBind();
        }

        protected void Store1_RefreshData(object sender, StoreRefreshDataEventArgs e)
        {
            BindTrash();
        }

        protected void btnTrashEmpty_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("ProductDelete");
                int record = 0;
                ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
                foreach (ProductCategory ac in bitEnt.ProductCategories.Where(ent => ent.IsDeleted == true))
                {
                    bitEnt.ProductCategories.DeleteObject(ac);
                    record++;

                }
                ShowNotification("Xóa" + record + " danh mục sản phẩm trong thùng rác thành công!");
                BindTrash();
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        protected void btnTrashDelete_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("ProductDelete");
                int record = 0;
                RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    ProductCategoryBLL.DeletePermanently(row.RecordID.ToInt32TryParse());
                    record++;
                }
                ShowNotification("Xóa" + record + " danh mục sản phẩm trong thùng rác thành công!");
                sm.ClearSelections();
                BindTrash();
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        protected void btnUnDelete_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("ProductEdit");
                ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
                RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    int ID = row.RecordID.ToInt32TryParse();
                    ProductCategory ac = bitEnt.ProductCategories.SingleOrDefault(ent => ent.CategoryID == ID);
                    if (ac != null)
                        ac.IsDeleted = false;
                }
                int record = bitEnt.SaveChanges();
                ShowNotification("Bỏ xóa" + record + " danh mục sản phẩm trong thùng rác thành công!");
                sm.ClearSelections();
                BindTrash();
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }
        #endregion
    }
}